package cc.fs.kotlin.ui.adapter;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.view.ViewGroup;

/**
 * Created by nekocode on 2015/6/11.
 * 暂时有个问题fragment实例是必须显示后，才能够初始化，不能一开始获取
 */
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    private Activity activity;
    private FragmentManager fragmentManager;
    private String[] titles;
    private Class[] classes;
    private Fragment[] fragments;
    private Bundle[] bundles;

    public MyFragmentPagerAdapter(Activity activity, String[] titles, Class[] classes, Bundle[] bundles) {
        super(activity.getFragmentManager());
        this.activity = activity;
        fragmentManager = activity.getFragmentManager();
        this.titles = titles;
        this.classes = classes;
        this.bundles = bundles;
        fragments = new Fragment[titles.length];
    }

    public MyFragmentPagerAdapter(Activity activity, String[] titles, Class[] classes) {
        super(activity.getFragmentManager());
        this.activity = activity;
        this.fragmentManager = activity.getFragmentManager();
        this.titles = titles;
        this.classes = classes;
        this.bundles = null;
        fragments = new Fragment[titles.length];
    }

    public Fragment getFragment(int position) {
        return fragments[position];
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Do we already have this fragment?
        String name = (String) getPageTitle(position);
        Fragment fragment = fragmentManager.findFragmentByTag(name);
        if (fragment != null && !fragment.isDetached()) {
            fragmentTransaction.detach(fragment);
        }

        fragment = getItem(position);
        fragmentTransaction.add(container.getId(), fragment, name);
        fragmentTransaction.commit();

        return fragment;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = Fragment.instantiate(activity, classes[position].getName(),
                bundles != null ? bundles[position] : null);
        fragments[position] = fragment;
        return fragment;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
}
